<template>
  <div>
    <div class="searchBar">
      <el-form label-width="100px">
      <div style="display:flex;">
        <el-form-item label="订单编号:">
          <el-input size="small" v-model="searchOrderNum"></el-input>
        </el-form-item>
        <el-form-item label="订单时间:">
          <el-date-picker
            v-model="searchTimeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            size="small">
          </el-date-picker>          
        </el-form-item>
        <!-- {{searchTimeRange}} -->
        <el-form-item label="订单状态:">
          <el-select v-model="searchOrderState" placeholder="请选择" size='small'>
            <el-option
              v-for="(item,index) in payStateOptions"
              :key="index"
              :label="item.label"
              :value="index">
            </el-option>
          </el-select>
          <!-- {{searchOrderState}} -->
        </el-form-item>
      </div>        
      </el-form>
      <div style="margin:0 auto;width:250px;">
          <el-button type="primary" class="el-icon-search" size="medium" @click="handleSearch(1)">搜索</el-button>
          <el-button class="el-icon-delete" size="medium" style="margin:20px 0 0 10px;" @click="handleSearch(0)">清空</el-button>
      </div>
    </div>

    <avue-crud ref="crud"
               :page="page"
               :data="dataList"
               :option="tableOption"
               @on-load="getDataList">

      <template slot="distributionType" slot-scope="scope">
        <span v-if="scope.row.distributionType==0">暂无</span>
        <span v-if="scope.row.distributionType==1">自提</span>
        <span v-if="scope.row.distributionType==2">美团配送</span>
        <span v-if="scope.row.distributionType==3">商家配送</span>
        <span v-if="scope.row.distributionType==4">快递</span>
      </template>

      <template slot="payState" slot-scope="scope">
        <template v-if="scope.row.orderState == 0">
          <span v-if="scope.row.status==1" class="info">未支付</span>
          <span v-else-if="scope.row.refundState==3" class="info">退款失败</span>
          <span v-else class="success">已支付</span>
        </template>
        <template v-if="scope.row.orderState == 1">
          <span v-if="scope.row.refundState==1" class="warning">退款待审核</span>
          <span v-else-if="scope.row.refundState==2" class="info">已退款</span>
          <span v-else class="info">已取消</span>  
        </template>
      </template>

      <template slot-scope="scope" slot="status">
        <template v-if="scope.row.orderState == 0">
          <span v-if="scope.row.refundState==3" class="info">退款失败</span>
          <span v-else-if="scope.row.status==1" class="primary">待支付</span>
          <span v-else-if="scope.row.status==2" class="warning">待发货</span>
          <span v-else-if="scope.row.status==3&&!scope.row.pickupTime" class="primary">待收货</span>
          <span v-else-if="scope.row.status==3&&scope.row.pickupTime" class="primary">待提货</span>
          <span v-else-if="scope.row.status==5" class="success">已收货</span>
          <span v-else-if="scope.row.status==6" class="success">已完成</span>
        </template>
        <template v-if="scope.row.orderState == 1">
          <span v-if="scope.row.refundState==0" class="info">订单已取消</span>
          <span v-if="scope.row.refundState==1" class="warning">退款待审核</span>
          <span v-if="scope.row.refundState==2" class="info">退款已完成</span>
        </template>
      </template>

      <template slot="menu" slot-scope="scope">
        <template v-if="userId!==1||(userId==1&&scope.row.shopId==1)">
          <el-button icon="edit" size="mini" @click="addOrUpdateHandle(scope.row.orderNumber)">查看订单</el-button>
          <el-button  v-if="scope.row.orderState==0&&scope.row.status==2&&!scope.row.pickupTime&&ifMeituanTranfer" type="primary" size="mini" @click="cancelMeituanTranfer">取消美团</el-button>
          <!-- <el-button  v-if="scope.row.orderState==0&&scope.row.status==2&&!scope.row.pickupTime&&scope.row.ifMeituanTranfer" type="primary" size="mini">取消美团</el-button> -->
          <el-popover
            v-if="scope.row.orderState==0&&scope.row.status==2&&!scope.row.pickupTime&&!ifMeituanTranfer"
            placement="top"
            width="200">
            <p>请选择配送方式</p>
            <div style="text-align: right; margin: 0">
              <el-button  size="mini" type="primary" @click="goShip(scope.row.orderNumber)">快递发货</el-button>
              <el-button type="primary" size="mini" @click="goTransfer(scope.row.orderNumber)">自行送货</el-button>
            </div>
            <!-- <el-button  v-if="scope.row.orderState==0&&scope.row.status==2&&!scope.row.pickupTime" type="primary" size="mini"  slot="reference">订单发货</el-button> -->
            <el-button type="primary" size="mini"  slot="reference">订单发货</el-button>
          </el-popover>

          <el-button v-if="scope.row.orderState==1&&scope.row.refundState==0" type="danger" size="mini" @click="handleDelete(scope.row.orderNumber)">删除订单</el-button>
          <!-- <el-button v-if="scope.row.orderState==0&&scope.row.status==2&&!scope.row.pickupTime" type="primary" size="mini" @click="goShip(scope.row.orderNumber)">订单发货</el-button> -->
          <el-button v-if="scope.row.orderState==0&&scope.row.status==2&&scope.row.pickupTime" type="primary" size="mini" @click="goStockUp(scope.row.orderNumber)">订单备货</el-button>
          <el-button v-if="scope.row.orderState==0&&(scope.row.status>=3||scope.row.status==1)" type="warning" size="mini" @click="showTransferInfo(scope.row)">订单跟踪</el-button>
        </template>
        <template v-else>
          <el-tag icon="edit" type="info" size="mini">不可更改</el-tag>
        </template>
      </template>

    </avue-crud>
    <consignment-info v-if="consignmentInfoVisible"
                  ref="consignmentInfo"
                  @inputCallback="getWaitingConsignmentExcel"></consignment-info>
    <add-or-update v-if="addOrUpdateVisible"
                   ref="addOrUpdate"
                   @refreshDataList="getDataList"></add-or-update>

    <devy-add v-if="devyVisible" ref="devyAdd"  @refreshDataList="getDataList"></devy-add>

    <el-dialog
      :title="transferInfo.deliverName"
      :visible.sync="transferVisible"
      modal
      center
      :close-on-click-modal='true'
      :close-on-press-escape='true'
      :before-close="handleClose"
      v-loading='transferLoading'>

      <div style="height: 300px;text-align:center;line-height:300px;font-size:20px;" v-if="selectOrder.status==1">
        等待买家付款
      </div>
      <div style="height: 300px;text-align:center;line-height:100px;font-size:20px;" v-else-if="selectOrder.pickupTime&&selectOrder.status==3">
        <div>等待用户自提，约定自提时间为</div>
        <div>{{selectOrder.pickupTime}}</div>
      </div>
      <div style="height: 300px;text-align:center;line-height:300px;font-size:20px;" v-else-if="selectOrder.status>=3&&selectOrder.pickupTime">
        买家已提货
      </div>
      <div v-else-if="selectOrder.status>=3&&!selectOrder.pickupTime">
        <el-steps direction="vertical"  :active="stepIndex" finish-status="success" process-status='wait'>
          <!-- <el-step v-for="item in (transferInfo.deliverData.Traces)" :title="item.AcceptStation" :description="item.AcceptTime">{{}}</el-step> -->
          <el-step v-for="(item,index) in (transferInfo.deliverData.Traces)" :key='index' :title="item.AcceptStation" :description="item.AcceptTime">{{}}</el-step>
        </el-steps>
      </div>
      <div v-else style="height: 300px;text-align:center;line-height:300px;font-size:20px;">
        暂无物流信息
      </div>
    </el-dialog>

  </div>
</template>

<script>
import AddOrUpdate from './orderInfo'
import ConsignmentInfo from './consignment-info'
import { tableOption } from '@/crud/order/order'  
import DevyAdd from './order-devy'
import orderRefundVue from './orderRefund.vue'

export default {
  data () {
    return {
      tableOption: tableOption,
      queryShopId :null,
      userId: null,
      dataForm: {},
      dateRange: [],
      shopNameAndId: [],
      devyVisible: false,
      transferVisible: false,
      transferLoading: true,
      ifMeituanTranfer: true,
      stepIndex: null,
      selectOrder:{},
      transferInfo: {
        deliverData:{}
      },
      resourcesUrl: window.SITE_CONFIG.resourcesUrl,
      dataList: [],
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 10 // 每页显示多少条
      },
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
      consignmentInfoVisible: false,
      
      searchOrderState:'',
      searchOrderNum: '',
      searchTimeRange: [],

      payStateOptions:[{
        label:'待支付',
        value:{orderState:0, status:1,}
      },{
        label:'待发货',
        value:{orderState:0, status:2,}
      },{
        label:'待收货/待提货',
        value:{orderState:0, status:3,}
      },{
        label:'已收货',
        value:{orderState:0, status:5,}
      },{
        label:'已完成',
        value:{orderState:0, status:6,}
      },{
        label:'已取消',
        value:{orderState:1, refundState:0,}
      },{
        label:'退款待审核',
        value:{orderState:1, refundState:1,}
      },{
        label:'退款已完成',
        value:{orderState:1, refundState:2,}
      },{
        label:'退款失败',
        value:{orderState:0, refundState:3,}
      },]
    }
  },
  computed:{},
  components: {
    AddOrUpdate,
    ConsignmentInfo,
    DevyAdd
  },
  activated () {   
    this.getDataList(this.page)   
    this.getShopNameAndId()

      //判断是否为admin 用户 
      this.$http({
        url: this.$http.adornUrl('/sys/user/info'),
        method: 'get',
        params: this.$http.adornParams()
      }).then(({data}) => { 
        console.log(data);
        this.userId = data.userId
      })
  },
  methods: {
    // 获取数据列表
    getDataList (page) {
      page = (page === undefined ? this.page : page)
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl('/order/order/page'),
        method: 'get',
        params: this.$http.adornParams(
          Object.assign({
            current: page.currentPage,
            size: page.pageSize,
            orderNumber: this.searchOrderNum,
            startTime: this.searchTimeRange.length!==0? this.dateTimeString(this.searchTimeRange[0]):'',
            endTime: this.searchTimeRange.length!==0? this.dateTimeString(this.searchTimeRange[1]):'',
          },this.searchOrderState!==''?this.payStateOptions[this.searchOrderState].value:{}), false
        )
      }).then((res) => {  
        let data = res.data
        this.dataList = data.records
        this.page.total = data.total
        this.dataListLoading = false
        // console.log(this.dataList);
      })
    },
    //获取商铺名和id对应列表
    getShopNameAndId(){
      this.$http({
        url:this.$http.adornUrl('/order/order/shopNameAndId'),
        method:'get',
      }).then((res) =>{
        this.shopNameAndId = res.data
      })
    },
    // 每页数
    sizeChangeHandle (val) {
      this.page.pageSize = val
      this.page.currentPage = 1
      this.getDataList(this.page)
    },
    // 当前页
    currentChangeHandle (val) {
      this.page.currentPage = val
      this.getDataList(this.page)
    },
    // 多选
    selectionChangeHandle (val) {
      this.dataListSelections = val
    },
    orderStatus () {

    },
    // 新增 / 修改
    addOrUpdateHandle (val) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(val)
      })
    },
    // 删除
    deleteHandle (id) {
      var ids = id ? [id] : this.dataListSelections.map(item => {
        return item.orderId
      })
      this.$confirm(`确定进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl(`/prod/spec/${ids}`),
          method: 'delete',
          data: this.$http.adornData(ids, false)
        }).then(({ data }) => {
          this.$message({
            message: '操作成功',
            type: 'success',
            duration: 1500,
            onClose: () => {
              this.getDataList(this.page)
            }
          })
        })
      }).catch(() => { })
    },

    showConsignmentInfo () {
      this.consignmentInfoVisible = true
      this.$nextTick(() => {
        this.$refs.consignmentInfo.init()
      })
    },

    getWaitingConsignmentExcel (consignmentInfo) {
      this.$http({
        url: this.$http.adornUrl('/order/order/waitingConsignmentExcel'),
        method: 'get',
        params: this.$http.adornParams({
          'consignmentName': consignmentInfo.consignmentName,
          'consignmentMobile': consignmentInfo.consignmentMobile,
          'consignmentAddr': consignmentInfo.consignmentAddr,
          'startTime': this.dateRange === null ? null : this.dateRange[0], // 开始时间
          'endTime': this.dateRange === null ? null : this.dateRange[1] // 结束时间
        }),
        responseType: 'blob' // 解决文件下载乱码问题
      }).then(({ data }) => {
        var blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
        const fileName = '待发货信息整理.xls'
        const elink = document.createElement('a')
        if ('download' in elink) { // 非IE下载
          elink.download = fileName
          elink.style.display = 'none'
          elink.href = URL.createObjectURL(blob)
          document.body.appendChild(elink)
          elink.click()
          URL.revokeObjectURL(elink.href) // 释放URL 对象
          document.body.removeChild(elink)
        } else { // IE10+下载
          navigator.msSaveBlob(blob, fileName)
        }
      })
    },
    getSoldExcel () {
      this.$http({
        url: this.$http.adornUrl('/order/order/soldExcel'),
        method: 'get',
        params: this.$http.adornParams({
          'startTime': this.dateRange === null ? null : this.dateRange[0], // 开始时间
          'endTime': this.dateRange === null ? null : this.dateRange[1] // 结束时间
        }),
        responseType: 'blob' // 解决文件下载乱码问题
      }).then(({ data }) => {
        var blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
        const fileName = '销售信息整理.xls'
        const elink = document.createElement('a')
        if ('download' in elink) { // 非IE下载
          elink.download = fileName
          elink.style.display = 'none'
          elink.href = URL.createObjectURL(blob)
          document.body.appendChild(elink)
          elink.click()
          URL.revokeObjectURL(elink.href) // 释放URL 对象
          document.body.removeChild(elink)
        } else { // IE10+下载
          navigator.msSaveBlob(blob, fileName)
        }
      })
    },

    // 发货
    goShip (orderNumber) {
      this.devyVisible = true
      this.$nextTick(() => {
        this.$refs.devyAdd.init(orderNumber, this.dataForm.dvyId, this.dataForm.dvyFlowId)
      })
    },
    // 备货
    goStockUp (orderNumber) {
      this.$confirm('确定备货完成？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl(`/order/order/delivery`),
          method: 'put',
          data: this.$http.adornData({
            orderNumber
          })
        }).then(({data}) => {
          this.$message({
            message: '操作成功',
            type: 'success',
            duration: 1500,
            onClose: () => {
              this.visible = false
              this.getDataList()
            }
          })
        })
      }).catch(() => {
      });
    },

    goTransfer(orderNumber){

    },

    cancelMeituanTranfer(orderNumber){
      console.log('cancel running');
      this.ifMeituanTranfer = false
    },

    showTransferInfo(order){
      this.transferVisible = true
      if (!order.pickupTime&&order.status>=3) {
        this.transferLoading = true
        this.$http({
          url:this.$http.adornUrl('/logistics/kuaidiniao/getLogisticsInformation'),
          method:'get',
          params: this.$http.adornParams({
            orderNumber: order.orderNumber
          })
        }).then(({data}) =>{
          this.transferInfo = data
          this.transferInfo.deliverData = JSON.parse(data.deliverData)
          this.stepIndex = this.transferInfo.deliverData.Traces.length
          console.log(this.transferInfo);
          // this.transferLoading = false
        })
      }
      this.selectOrder = order
    },

    handleClose(done){
      this.transferInfo= {
        deliverData:{}
      }
      this.pickupTime = ''
      done()
    },

    handleDelete(orderNumber){
      this.$confirm("确认删除此笔订单？",'提示').then(() =>{
        this.$http({
          url: this.$http.adornUrl('/order/order/deleteOrderByStore'),
          method: 'put',
          params: this.$http.adornParams({
            orderNumber
          })
        }).then((res) =>{
          if (res == true) {
            this.$message({
              message: "已删除",
              type: 'success'
            })
            this.getDataList()
          }
        })
      }).catch(() =>{
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },

    handleSearch(state){
      if (state==0) {
        this.searchOrderNum = ''
        this.searchOrderState = ''
        this.searchTimeRange = []
        this.getDataList()
      }else if (state == 1) {
        // console.log(this.searchTimeRange);
        // var params = Object.assign({
          // orderNumber: this.searchOrderNum,
        // })
        // },this.searchOrderState?this.payStateOptions[this.searchOrderState].value:{})
        // console.log(params);
        this.getDataList()
      }
    },

		//格式化日期时间
		dateTimeString(val){
      let date = new Date(val)
      // console.log(date);
			let D = [
			String(date.getFullYear()),
			date.getMonth()<9?'0'+(date.getMonth()+1):String(date.getMonth()+1),
			date.getDate()<10?'0'+date.getDate():String(date.getDate()),
			date.getHours()<10?'0'+date.getHours():String(date.getHours()),
			date.getMinutes()<10?'0'+date.getMinutes():String(date.getMinutes()),
			date.getSeconds()<10?'0'+date.getSeconds():String(date.getSeconds())
      ]
      // console.log(D.slice(0,3).join('-')+' '+D.slice(3).join(':'));
			return D.slice(0,3).join('-')+' '+D.slice(3).join(':')  
		},    

  }
}
</script>
<style lang="scss" scoped>
.content{
  font-size: 14px;
}

.info{
  color: #909399;
}
.danger{
  color: #F56C6C;
}
.warning{
  color: #E6A23C;
}
.success{
  color: #67C23A;
}
.danger-off{
  color: #FDE2E2;
}
.primary{
  color: #409EFF;
}
.el-input{
  width: 250px;
}
.searchBar .el-button{
  margin: 0 auto;
}
.el-button+.el-button{
  margin-left: 0;
}

</style>
